using MediatR;
using Microsoft.EntityFrameworkCore;
using Medical.Domain;
using Medical.ErrorCode;
using Medical.Infrastructrue.Interfaces;
using Medical.ReadApi.Appcontext.Command;
using Medical.ReadApi.Dto;

namespace Medical.ReadApi.Appcontext.CommandHandler
{
	public class GetPermissionsListQueryHandler : IRequestHandler<GetPermissionsListQuery, ApiPaging<PermissionDto>>
	{
		private readonly IBaseRepository<Permission> _repo;

		public GetPermissionsListQueryHandler(IBaseRepository<Permission> repo)
		{
			_repo = repo;
		}

		public async Task<ApiPaging<PermissionDto>> Handle(GetPermissionsListQuery request, CancellationToken cancellationToken)
		{
			var query = _repo.GetAll();
			if (!string.IsNullOrEmpty(request.Group)) query = query.Where(x => ((Permission)x).Group == request.Group);
			if (request.IsActive.HasValue) query = query.Where(x => ((Permission)x).IsActive == request.IsActive.Value);
			var totalCount = await query.CountAsync(cancellationToken);
			var items = await query.OrderBy(x => ((Permission)x).Group).ThenBy(x => ((Permission)x).Name)
				.Skip((request.Page - 1) * request.Size).Take(request.Size)
				.Select(x => (Permission)x)
				.Select(p => new PermissionDto { PermissionId = p.PermissionId, Name = p.Name, Code = p.Code, Group = p.Group, Description = p.Description, IsMenu = p.IsMenu, IsActive = p.IsActive, CreatedAt = p.CreatedAt, UpdatedAt = p.UpdatedAt })
				.ToListAsync(cancellationToken);
			var totalPage = (int)Math.Ceiling(totalCount / (double)request.Size);
			return new ApiPaging<PermissionDto> { totalCount = totalCount, totalPage = totalPage, data = items };
		}
	}
}
